//
//  SKUSelectView.swift
//  Owner
//
//  Created by xiaoZuDeMeng on 2021/1/5.
//  Copyright © 2021 Selina. All rights reserved.
//

import UIKit
import Reusable

class SKUSelectView: UIView {

    private var dataSource: [PropertiesItem] = []
        
    private var callBack: CallBack?
    
    private var selectedItem: PropertiesItem?
    
    private let skuImageHeight = 105/375*SCREEN_WIDTH
    
    private lazy var maskview: UIButton = {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        button.backgroundColor = UIColor(white: 0, alpha: 0.6)
        button.addTarget(self, action:#selector(clickAction), for: UIControl.Event.touchUpInside)
        
        return button
    }()
    
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        iv.backgroundColor = Theme.kPlaceholderImage
        iv.addRadius(8)
        
        return iv
    }()
    
    private lazy var price: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        label.textColor = Theme.colorOrnament
        
        return label
    }()
    
    private lazy var points: GBorderLabel = {
        let label = GBorderLabel()
        label.font = UIFont.systemFont(ofSize: 12, weight: .regular)
        label.textColor = Theme.colorOrnament
        label.textAlignment = .left
        label.backgroundColor = Theme.colorOrnament.withAlphaComponent(0.06)
        label.textInset = UIEdgeInsets(top: 2, left: 5, bottom: 2, right: 5)
        label.addRadius(8)
        
        return label
    }()
    
    private lazy var close: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "sku_close"), for: .normal)
        button.addTarget(self, action: #selector(closeAction), for: .touchUpInside)

        return button
    }()
    
    private lazy var collectionView: UICollectionView = {
        
        let flowLayout = SKUItemsLayout()
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        cv.backgroundColor = .white
        cv.delegate = self
        cv.dataSource = self
        cv.register(cellType: SKUCell.self)
        cv.register(supplementaryViewType: SKUHeader.self, ofKind: UICollectionView.elementKindSectionHeader)
        cv.register(supplementaryViewType: SKUFooter.self, ofKind: UICollectionView.elementKindSectionFooter)
        cv.addSubview(title)
        cv.contentInset = UIEdgeInsets(top: 48, left: 0, bottom: 0, right: 0);
        
        return cv
    }()
    
    private lazy var confirm: GSubmitButton = {
        let button = GSubmitButton()
        button.addTarget(self, action: #selector(confirmAction), for: .touchUpInside)
        button.setTitle("确定".localized(), for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14.0, weight: .bold)
        button.layer.cornerRadius = 22.0
        button.layer.masksToBounds = true
        
        return button
    }()
    
    private lazy var title: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: -48, width: SCREEN_WIDTH - 32, height: 48))
        label.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        label.textColor = Theme.textColorPrimary
        label.text = "规格"
        label.textAlignment = .left
        
        return label
    }()
        
    //MARK: -------------------init----------------------
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayout()
    }
    
    private func setupLayout() {
        
        self.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.top.equalTo(24)
            make.left.equalTo(16)
            make.size.equalTo(CGSize(width: skuImageHeight, height: skuImageHeight))
        }
        
        self.addSubview(close)
        close.snp.makeConstraints { (make) in
            make.top.equalTo(12)
            make.right.equalTo(0)
            make.size.equalTo(CGSize(width: 48, height: 48))
        }
        
        self.addSubview(price)
        price.snp.makeConstraints { (make) in
            make.top.equalTo(28)
            make.left.equalTo(imageView.snp.right).offset(12)
            make.right.equalTo(close.snp.left).offset(-5)
        }
        
        self.addSubview(points)
        points.snp.makeConstraints { (make) in
            make.top.equalTo(price.snp.bottom).offset(5)
            make.left.equalTo(price.snp.left)
            make.height.equalTo(17)
        }
        
        self.addSubview(confirm)
        confirm.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: SCREEN_WIDTH - 32, height: 44))
            make.bottom.equalTo(-34)
        }
        
        self.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(imageView.snp.bottom).offset(12)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(confirm.snp.top).offset(-16)
        }
    }
    
    private func updateData(_ data: PropertiesItem?) {
        
        imageView.sd_setImage(with: URL(string: data?.pic ?? ""))

        points.isHidden = data?.saleCashForShow == nil || data?.saleCashForShow == "" || data?.saleCashForShow == nil || data?.saleCashForShow == ""
        
        if data?.saleCashForShow != nil && data?.saleCashForShow != "" {
            price.attributedText = data?.priceAttri
            points.attributedText = data?.pointsAttriOnPoints
        } else {
            price.attributedText = data?.pointsAttri
        }
        
        collectionView.reloadData()
    }
    
    public func show(_ datas: [PropertiesItem]) {
        
        UIApplication.shared.windows[0].addSubview(maskview)
        UIApplication.shared.windows[0].addSubview(self)
        
        var totalWidth: CGFloat = 0.0  //所有标签 + 间隔 的长度
        for item in datas {
            totalWidth += (item.size.width + 6)
        }
        let line = ceil(totalWidth/(SCREEN_WIDTH - 32))
        let cvHieght = 40*line  //collectionView高度
        
        var totalHeight = skuImageHeight + 242 + cvHieght // 242 为除collectionview以外的总高度
        
        totalHeight = totalHeight > SCREEN_HEIGHT*0.6 ? SCREEN_HEIGHT*0.6 : totalHeight //最高为屏幕高度60%
        
        self.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: totalHeight)
        
        var frame = self.frame
        frame.origin.y = self.superview!.bounds.size.height - self.frame.size.height
        self.maskview.alpha = 0
        
        dataSource = datas
        
        if selectedItem != nil {
            updateData(selectedItem)
        } else if datas.count > 0 {
            var idx = 0
            selectedItem = datas[0]
            for (index, item) in datas.enumerated() {
                if item.selected == true {
                    idx = index
                    selectedItem = item
                    break
                }
            }
            updateData(datas[idx])
        }
             
        collectionView.reloadData()
        
        UIView.animate(withDuration: 0.3, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: {}) { (Bool) in
                UIView.animate(withDuration: 0.3, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: {
                    self.maskview.alpha = 1.0
                    self.frame = frame
                    }, completion: { (Bool) in
            })
        }
    }
    
    public func show(_ datas: [PropertiesItem], callBack: @escaping CallBack) {
        self.callBack = callBack
        show(datas)
    }

    private func dismissPop(_ item: PropertiesItem?) {

        var frame = self.frame
        frame.origin.y += self.frame.size.height
        
        self.callBack?(item)
        
        UIView.animate(withDuration: 0.3, animations: {
            self.frame = frame
            self.maskview.alpha = 0.0
            }) { (Bool) in
                UIView.animate(withDuration: 0.3, delay: 0, options: UIView.AnimationOptions.curveEaseInOut, animations: {}, completion: { (Bool) in
                    self.removeFromSuperview()
                    self.maskview.removeFromSuperview()
            })
        }
    }
    
    //MARK: --------------------@objc--------------------
    @objc private func clickAction() {
        dismissPop(nil)
    }
    
    @objc private func confirmAction() {

        var flag = false
        
        for item in dataSource {
            if item.selected == true {
                flag = true
                selectedItem?.totalPoints = (selectedItem?.singlePoints ?? 0)!*(selectedItem?.count ?? 1)
                selectedItem?.totalCash = (selectedItem?.singleCash ?? 0.0)!*CGFloat(selectedItem?.count ?? 1)
                break
            }
        }
        
        if flag == false {
            HUDManager.showTipText("请选择规格")
            return
        }
        
        self.dismissPop(selectedItem)
    }
    
    @objc private func closeAction() {
        self.dismissPop(nil)
    }
}

extension SKUSelectView: UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    //MARK: ----------UICollectionViewDataSource----------
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: SKUCell.self)
        cell.configCell(model: dataSource[indexPath.row]) { [self]  it  in
       
            let item = dataSource[indexPath.row]
            if item.stocks ?? 0 < 1 {
                HUDManager.showTipText("没有库存啦~")
                return
            }
            
            if item.selected == false {
                item.selected = true
                updateData(item)
            }
            
            for (idx, item) in dataSource.enumerated() {
                if idx != indexPath.row && item.stocks ?? 0 > 0 {
                    if item.selected == true {
                        item.selected = false
                        item.count = 1   //未选择的规格，数目归1
                    }
                }
            }
            
            selectedItem = item
            self.collectionView.reloadData()
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, for: indexPath, viewType: SKUHeader.self)
            return header
        } else if kind == UICollectionView.elementKindSectionFooter {
            let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, for: indexPath, viewType: SKUFooter.self)
            footer.updateFooter(selectedItem) { [self] count in
                selectedItem?.count = count as? Int
            }
            return footer
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: SCREEN_WIDTH, height: 64)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        Log.info("didSelectItemAt --------------")
    }
        
    //MARK: ----------UICollectionViewDelegateFlowLayout----------
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return dataSource[indexPath.row].size
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 4, left: 0, bottom: 8, right: 6)
    }
}

